<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8"/>
    <title>java</title>
    <link rel="stylesheet" th:href="@{/css/myStyle.css}"/>
</head>
<body xmlns:th="http://www.thymeleaf.org">
    <div class="n-head">
        <div class="g-doc f-cb">
            <div class="user">
                卖家你好，<span class="name">seller</span>！<a href="/logout">[退出]</a>
            </div>
            <ul class="nav">
                <li><a href="/">首页</a></li>
                <li><a href="/publish">发布</a></li>
            </ul>
        </div>
    </div>
    <div class="g-doc">
        <div class="m-tab m-tab-fw m-tab-simple f-cb">
            <h2 id="pub">内容发布</h2>
        </div>
        <div class="n-public">
            <div class="m-form m-form-ht" id="form">
                <div class="fmitem">
                    <label class="fmlab">标题：</label>
                    <div class="fmipt">
                        <input class="u-ipt ipt" id="title" name="title" autofocus placeholder="2-80字符" onblur="check(this)"/>
                        <p style="display: none; color: red">字数不符</p>
                    </div>
                </div>
                <div class="fmitem">
                    <label class="fmlab">摘要：</label>
                    <div class="fmipt">
                        <input class="u-ipt ipt" id="summary" name="summary" placeholder="2-140字符" onblur="check(this)"/>
                        <p style="display: none; color: red">字数不符</p>
                    </div>
                </div>
                <div class="fmitem">
                    <label class="fmlab">图片：</label>
                    <div class="fmipt" id="uploadType">
                        <input name="pic" type="radio" id="urlType" value="url" onclick="shift(this)" checked /> 图片地址
                        <input name="pic" type="radio" id="fileType" value="file" onclick="shift(this)" /> 本地上传
                    </div>
                </div>
                <div class="fmitem">
                    <label class="fmlab"></label>
                    <div class="fmipt" id="urlUpload">
                        <input class="u-ipt ipt" id="image" name="image" oninput="urlInput()" placeholder="图片地址"/>
                    </div>
                    <div class="fmipt" id="fileUpload"  style="display:none">
                        <input class="u-ipt ipt" id="fileUp" name="file" type="file" accept="image/*"/>
                        <button class="u-btn u-btn-primary" id="upload" onclick="imgUpload()">上传</button>
                    </div>
                </div>
                <div class="fmitem">
                    <label class="fmlab">正文：</label>
                    <div class="fmipt">
                        <textarea class="u-ipt" id="detail" name="detail" rows="10" placeholder="2-1000个字符" onblur="check(this)"></textarea>
                        <p style="display: none; color: red">字数不符</p>
                    </div>
                </div>
                <div class="fmitem">
                    <label class="fmlab">价格：</label>
                    <div class="fmipt">
                        <input class="u-ipt price" id="price" name="price" onblur="check(this)"/>元
                        <p style="display: none; color: red">请输入合法价格</p>
                    </div>
                </div>
                <div class="fmitem fmitem-nolab fmitem-btn">
                    <div class="fmipt">
                        <button id="pubBtn" type="submit" class="u-btn u-btn-primary u-btn-lg" onclick="submit()">发 布</button>
                    </div>
                </div>
            </div>
            <span class="imgpre">
                <img th:src="@{/image/NoPic.png}" onerror="javascript:this.src = '/image/NoPic.png';" alt="" id="imgpre">
            </span>
        </div>
    </div>
    <div class="n-foot">
        <p>
            杭研有数：陈佳——在校作业
        </p>
    </div>
</body>
</html>
<script>
    var title = document.getElementById("title");
    var summary = document.getElementById("summary");
    var urlType = document.getElementById("urlType");

    var urlUpload = document.getElementById("urlUpload");
    var imgUrlInput = document.getElementById("image");

    var fileUpload = document.getElementById("fileUpload");
    var imgFileInput = document.getElementById("fileUp");

    var detail = document.getElementById("detail");
    var price = document.getElementById("price");
    var imgUrlSrc = document.getElementById("imgpre");
    var time = new Date().getTime();

    var isFirst = true;
    var id = -1;

    var txt = document.getElementById("pub");
    var btn = document.getElementById("pubBtn");

    var canSend = new Array();
    (function () {
        if("[[${commodity.title}]]" != null && "[[${commodity.title}]]" !== ""){
            isFirst = false;
            title.textContent = "[[${commodity.title}]]";
            title.value = "[[${commodity.title}]]";
            summary.textContent = "[[${commodity.summary}]]";
            summary.value = "[[${commodity.summary}]]";
            detail.textContent = "[[${commodity.description}]]";
            detail.value = "[[${commodity.description}]]";
            price.textContent = "[[${commodity.price}]]";
            price.value = "[[${commodity.price}]]";
            imgUrlSrc.src = "[[${commodity.picUrl}]]";
            imgUrlSrc.value = "[[${commodity.picUrl}]]";
            imgUrlInput.textContent = "[[${commodity.picUrl}]]";
            imgUrlInput.value = "[[${commodity.picUrl}]]";

            txt.textContent="内容编辑";
            btn.textContent = "保 存";
            id = "[[${commodity.id}]]";

        }
    })();

    function shift(thisClick) {
        if((thisClick.checked === true) ^ (thisClick.value === "file")){
            urlUpload.style.display = "block";
            fileUpload.style.display = "none";
        }else{
            urlUpload.style.display = "none";
            fileUpload.style.display = "block";
        }
    }


    function urlInput() {
        imgUrlSrc.src = imgUrlInput.value;
    }


    function imgUpload() {
        var imgName = time + imgFileInput.files[0].name;
        var type = imgName.substring(imgName.lastIndexOf(".") + 1).toLowerCase();
        if(imgFileInput.files[0].size > 1000000){
            alert("超过文件上传大小限制");
        }else if(type !== "png" && type !== "jpg"){
            alert("只能上传png，jpg的文件");
        }else{
            imgUrlSrc.src = window.URL.createObjectURL(imgFileInput.files[0]);
        }
    }


    function submit() {
        var send = true;
        var data = new FormData();

        if(title.value && canSend["title"]){
            data.append('title', title.value);
            title.classList.remove('z-err');
        }else{
            send = false;
            title.classList.add('z-err');
        }
        if(summary.value && canSend["summary"]){
            data.append('summary', summary.value);
            summary.classList.remove('z-err');
        }else{
            send = false;
            summary.classList.add('z-err');
        }
        if(detail.value && canSend["detail"]){
            data.append('detail', detail.value);
            detail.classList.remove('z-err');
        }else{
            send = false;
            detail.classList.add('z-err');
        }
        if(price.value && canSend["price"]){
            data.append('price', price.value);
            price.classList.remove('z-err');
        }else{
            send = false;
            price.classList.add('z-err');
        }

        if(urlType.checked){
            if(imgUrlInput.value){
                data.append('url', imgUrlInput.value);
                data.append('file', '');
                imgUrlInput.classList.remove('z-err');
            }else{
                send = false;
                imgUrlInput.classList.add('z-err');
            }
        }else{
            if(imgFileInput.files[0]){
                var imgName = time + imgFileInput.files[0].name;
                data.append('url', '');
                data.append('file',imgName);
                imgFileInput.classList.remove('z-err');
            }else{
                send = false;
                imgFileInput.classList.add('z-err');
            }
        }
        data.append('id', id);
        data.append('isFirst', isFirst);
        if(isFirst){
            data.append('publishDate', time.toString());
        }else{
            data.append('modifyDate', time.toString());
        }

        if(send){
            var xhr = new XMLHttpRequest();

            if(imgFileInput.files[0]){
                xhr.open("POST", "/uploadImg", true);
                var picData = new FormData();
                console.log(imgName);
                picData.append("file", imgFileInput.files[0], imgName);
                picData.enctype = "multipart/form-data";
                xhr.send(picData);
                xhr.onload = function () {
                    if (this.readyState === 4 && this.status === 200) {
                        var request = new XMLHttpRequest();
                        request.open("POST", "/submit", true);
                        var dataJSON = {};
                        data.forEach((value, key) => dataJSON[key] = value);
                        request.send(JSON.stringify(dataJSON));
                        request.onload = function () {
                            if (request.readyState === 4 && request.status === 200) {
                                window.location.href="/success?id=" + request.responseText + "&isFirst=" + isFirst;
                            } else {
                                alert('An error occurred!');
                            }
                        };
                    } else {
                        alert('An error occurred!');
                    }
                };
            }else{
                xhr.open("POST", "/submit", true);
                var dataJSON = {};
                data.forEach((value, key) => dataJSON[key] = value);
                xhr.send(JSON.stringify(dataJSON));
                xhr.onload = function () {
                    if (this.readyState === 4 && this.status === 200) {
                        window.location.href="/success?id=" + this.responseText + "&isFirst=" + isFirst;
                    } else {
                        alert('An error occurred!');
                    }
                };
            }
        }
    }


    function check(obj) {
        switch (obj.id) {
            case "title":
                if(obj.value.length < 2 || obj.value.length > 80){
                    obj.parentElement.children[1].style.display='block';
                    canSend["title"] = false;
                }else{
                    obj.parentElement.children[1].style.display='none';
                    canSend["title"] = true;
                    obj.classList.remove('z-err');
                }
                break;
            case "summary":
                if(obj.value.length < 2 || obj.value.length > 140){
                    obj.parentElement.children[1].style.display='block';
                    canSend["summary"] = false;
                }else{
                    obj.parentElement.children[1].style.display='none';
                    canSend["summary"] = true;
                    obj.classList.remove('z-err');
                }
                break;
            case "detail":
                if(obj.value.length < 2 || obj.value.length > 1000){
                    obj.parentElement.children[1].style.display='block';
                    canSend["detail"] = false;
                }else{
                    obj.parentElement.children[1].style.display='none';
                    canSend["detail"] = true;
                    obj.classList.remove('z-err');
                }
                break;
            case "price":
                var reg=/^[0-9]+.?[0-9]*$/;
                if(!reg.test(obj.value)){
                    obj.parentElement.children[1].style.display='block';
                    canSend["price"] = false;
                }else{
                    obj.parentElement.children[1].style.display='none';
                    canSend["price"] = true;
                    obj.classList.remove('z-err');
                }
                break;
            default: break;
        }
    }

</script>
